package org.robert.export_client.excel.util;

import org.robert.export_client.excel.metadata.ExcelHeadEntity;

import java.util.*;

/**
 * @Description 可以获取到一个根据index排序的有序map
 * @Author robert
 * @Date 2024/1/22 21:09
 **/
public class MapUtil {

    public static TreeMap<String, List<ExcelHeadEntity>> getSortMap(List<ExcelHeadEntity> list){
        // 创建一个TreeMap，键是index，值是一个包含所有具有相同index的对象的列表
        TreeMap<String, List<ExcelHeadEntity>> sortedMap = new TreeMap<>();
        HashMap<String, String> cacheKeyMap = new HashMap<>();
        for (ExcelHeadEntity entity : list) {
            String key = entity.getColumnIndex() + "_" + entity.getFieldName();
            boolean flag = false;
            for (String s : sortedMap.keySet()) {
                String[] arr = s.split("_");
                if(arr[1].equals(entity.getFieldName())){
                    flag = true;
                    key = cacheKeyMap.get(arr[1]);
                }
            }
            if(flag){
                List<ExcelHeadEntity> excelHeadEntities = sortedMap.get(key);
                List<ExcelHeadEntity> objects = new ArrayList<>();
                objects.addAll(excelHeadEntities);
                objects.add(entity);
                sortedMap.put(key, objects);
            }else{
                if(!cacheKeyMap.containsKey(entity.getFieldName())){
                    cacheKeyMap.put(entity.getFieldName(), key);
                }

                sortedMap.put(key, Arrays.asList(entity));
            }
        }
        return sortedMap;
    }
}
